package com.cdy.client.netty;

import com.cdy.common.command.Command;
import com.cdy.common.command.UploadCommand;
import com.cdy.common.serialize.HessionSerialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端编码器
 * Created by 陈东一
 * 2019/10/20 0020 19:09
 */
@Slf4j
@ChannelHandler.Sharable
public class ClientEncodeHandler extends MessageToByteEncoder<Command> {
    private final HessionSerialize serialize = new HessionSerialize();

    @Override
    protected void encode(ChannelHandlerContext ctx, Command msg, ByteBuf out) throws Exception {
        log.info("client encode {}",msg.toString());

        if (msg instanceof UploadCommand) {
            ByteBuf buf = ((UploadCommand) msg).getByteBuf();
            ((UploadCommand) msg).setByteBuf(null);
            byte[] serialize = this.serialize.serialize((UploadCommand) msg, UploadCommand.class);
            out.writeInt(serialize.length + Math.toIntExact(((UploadCommand) msg).getLength()));
            out.writeInt(serialize.length);
            out.writeBytes(serialize);
            out.writeBytes(buf);
        } else {
            byte[] serialize = this.serialize.serialize((Command) msg, Command.class);
            out.writeInt(serialize.length);
            out.writeInt(serialize.length);
            out.writeBytes(serialize);
        }
    }
}
